from flask import render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from . import settings
from .. import db
from ..models import User, UserNotificationSettings, SystemSettings

@settings.route('/settings')
@login_required
def settings_index():
    return render_template('settings/index.html', title='系统设置')

@settings.route('/settings/profile', methods=['GET', 'POST'])
@login_required
def profile_settings():
    if request.method == 'POST':
        # 检查用户名是否已存在
        if current_user.username != request.form.get('username'):
            existing_user = User.query.filter_by(username=request.form.get('username')).first()
            if existing_user:
                flash('用户名已存在', 'danger')
                return redirect(url_for('settings.profile_settings'))
        
        # 检查邮箱是否已存在
        if current_user.email != request.form.get('email'):
            existing_email = User.query.filter_by(email=request.form.get('email')).first()
            if existing_email:
                flash('邮箱已存在', 'danger')
                return redirect(url_for('settings.profile_settings'))
        
        current_user.username = request.form.get('username')
        current_user.email = request.form.get('email')
        
        # 如果提供了新密码则更新密码
        new_password = request.form.get('new_password')
        if new_password:
            current_user.password = new_password
        
        try:
            db.session.commit()
            flash('个人信息更新成功', 'success')
        except Exception as e:
            db.session.rollback()
            flash('更新失败，请稍后重试', 'danger')
            
        return redirect(url_for('settings.settings_index'))
    
    return render_template('settings/profile.html', title='个人信息设置')

@settings.route('/settings/notification', methods=['GET', 'POST'])
@login_required
def notification_settings():
    # 获取或创建用户的通知设置
    settings = UserNotificationSettings.query.filter_by(user_id=current_user.id).first()
    if not settings:
        settings = UserNotificationSettings(user_id=current_user.id)
        db.session.add(settings)
        db.session.commit()
    
    if request.method == 'POST':
        try:
            # 更新设置
            settings.device_offline = bool(request.form.get('device_offline'))
            settings.device_error = bool(request.form.get('device_error'))
            settings.water_quality = bool(request.form.get('water_quality'))
            settings.water_pressure = bool(request.form.get('water_pressure'))
            settings.maintenance_reminder = bool(request.form.get('maintenance_reminder'))
            settings.inspection_reminder = bool(request.form.get('inspection_reminder'))
            
            db.session.commit()
            flash('通知设置更新成功', 'success')
            return redirect(url_for('settings.settings_index'))
        except Exception as e:
            db.session.rollback()
            flash('设置更新失败，请稍后重试', 'danger')
    
    return render_template('settings/notification.html', 
                         title='通知设置',
                         settings=settings)

@settings.route('/settings/system', methods=['GET', 'POST'])
@login_required
def system_settings():
    settings = SystemSettings.get_settings()
    
    if request.method == 'POST':
        try:
            # 更新水质阈值设置
            settings.ph_min = float(request.form.get('ph_min'))
            settings.ph_max = float(request.form.get('ph_max'))
            settings.turbidity_threshold = float(request.form.get('turbidity_threshold'))
            
            # 更新设备监控设置
            settings.offline_threshold = int(request.form.get('offline_threshold'))
            settings.data_collection_interval = int(request.form.get('data_collection_interval'))
            
            # 更新维护计划设置
            settings.routine_inspection_interval = int(request.form.get('routine_inspection_interval'))
            settings.full_maintenance_interval = int(request.form.get('full_maintenance_interval'))
            
            db.session.commit()
            flash('系统参数更新成功', 'success')
            return redirect(url_for('settings.settings_index'))
        except ValueError:
            flash('请输入有效的数值', 'danger')
        except Exception as e:
            db.session.rollback()
            flash('设置更新失败，请稍后重试', 'danger')
    
    return render_template('settings/system.html', 
                         title='系统参数设置',
                         settings=settings) 